<template>
  <el-card shadow="hover">
    <!-- 题目区 -->
    <el-row class="question-title m-b-20" :gutter="10">
      <el-col :span="12">
        <el-radio-group v-model="questionInfo.type" @input="changeType">
          <el-radio-button label="0">单选</el-radio-button>
          <el-radio-button label="1">多选</el-radio-button>
          <el-radio-button label="2">判断</el-radio-button>
          <el-radio-button label="3">填空</el-radio-button>
          <el-radio-button label="4">主观</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="6">
        <strong class="m-r-5">分值:</strong><el-input-number v-model="questionInfo.score" size="small" :min="1" :max="30"></el-input-number>
      </el-col>
      <el-col :span="6">
        <span class="fr">
          <strong>难度:</strong><el-rate v-model="questionInfo.difficulty" text-color="#ff9900"></el-rate>
        </span>
      </el-col>
    </el-row>
    <el-divider />
    <el-row class="m-t-20">
      <el-col :span="2"><strong>题目：</strong></el-col>
      <el-col :span="22">
        <tinymce-editor ref="tinymce" v-model="questionInfo.content"
          :content="questionInfo.content"
          :plugins="[]"
          :toolbar="toolbar"
          :menubar="false"
          :height="150"
          @input="renderOption"
        />
      </el-col>
    </el-row>
    <!-- 作题区 -->
    <el-row class="question-options m-t-20">
      <el-col v-if="['0', '1'].indexOf(questionInfo.type) !== -1" :span="2"><strong>选项：</strong></el-col>
      <el-col v-else :span="2"><strong>答案：</strong></el-col>
      <el-col v-if="['0', '1'].indexOf(questionInfo.type) !== -1" :span="22">
        <el-popover width="650" placement="right" v-model="optionDialogVisible">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-input v-model="current_option_value" placeholder="请输入选项值" />
            </el-col>
            <el-col :span="12">
              <el-radio-group v-model="current_option_type">
                <el-radio label="0">文字</el-radio>
                <el-radio label="1">图片</el-radio>
                <el-radio label="2">音频</el-radio>
              </el-radio-group>
            </el-col>
            <el-col v-if="current_option_type == '0'" class="m-t-20" :span="24">
              <el-input v-model="current_option_label" placeholder="请输入选项内容" />
            </el-col>
            <el-col v-if="current_option_type != '0'" class="m-t-20" :span="24">
              <file-viewer ref="file_viewer" v-model="current_option_src" :list-type="'text'" :show-file-list="true" :limit="1" />
            </el-col>
          </el-row>
          <el-row class="m-t-20 m-b-10 align-center">
            <el-button size="mini" type="text" @click="closeOptionDialog">取消</el-button>
            <el-button size="mini" type="primary" @click="addOptionConfirm">确定</el-button>
          </el-row>
          <el-button slot="reference" type="primary" icon="el-icon-plus" circle @click.stop="addOption"></el-button>
        </el-popover>
        <el-link class="fr" type="danger" :underline="false" @click="clearOption">清空</el-link>
      </el-col>
      <!-- 单选 -->
      <el-col v-if="questionInfo.type == '0'" :span="22" :offset="2">
        <div class="question-options-item">
          <text-select v-if="questionInfo.optionType == '0'" :value="questionInfo.answer" :options="questionInfo.options" :direction="'vertical'" @input="combineAnswer" />
          <image-select v-if="questionInfo.optionType == '1'" :value="questionInfo.answer" :options="questionInfo.options" @input="combineAnswer" />
          <audio-select v-if="questionInfo.optionType == '2'" :value="questionInfo.answer" :options="questionInfo.options" :direction="'vertical'" @input="combineAnswer" />
        </div>
      </el-col>
      <!-- 多选 -->
      <el-col v-if="questionInfo.type == '1'" :span="22" :offset="2">
        <div class="question-options-item">
          <text-select v-if="questionInfo.optionType == '0'" multiple :value="optionsAnswer" :options="questionInfo.options" :direction="'vertical'" @input="combineCheckboxAnswer" />
          <image-select v-if="questionInfo.optionType == '1'" multiple :value="optionsAnswer" :options="questionInfo.options" @input="combineCheckboxAnswer" />
          <audio-select v-if="questionInfo.optionType == '2'" multiple :value="optionsAnswer" :options="questionInfo.options" :direction="'vertical'" @input="combineCheckboxAnswer" />
        </div>
      </el-col>
      <!-- 判断 -->
      <el-col v-if="questionInfo.type == '2'" :span="22" :offset="2">
        <el-radio v-model="questionInfo.answer" label="Y">对</el-radio>
        <el-radio v-model="questionInfo.answer" label="N">错</el-radio>
      </el-col>
      <!-- 填空 -->
      <el-col v-if="questionInfo.type == '3'" :span="22" :offset="2">
        <div class="blank_option-item" v-for="(option, index) in questionInfo.options" :key="'option_blank_' + index">
          <strong>第{{ index + 1 }}空：</strong>
          <el-input v-model="option.value" class="underline" style="width: 150px;" @input="combineBlankAnswer" />
        </div>
      </el-col>
      <!-- 主观题 -->
      <el-col v-if="questionInfo.type == '4'" :span="22" :offset="2">
        <el-input
          type="textarea"
          :rows="5"
          placeholder="请输入答案"
          v-model="questionInfo.answer">
        </el-input>
      </el-col>
    </el-row>
    <!-- 解析区 -->
    <el-row class="analysis m-t-20">
      <el-col :span="2"><strong>解析：</strong></el-col>
      <el-col :span="22">
        <tinymce-editor ref="tinymce" v-model="questionInfo.analysis"
          :content="questionInfo.analysis"
          :plugins="[]"
          :toolbar="'bold italic underline strikethrough blockquote|forecolor backcolor | alignleft aligncenter alignright alignjustify | undo redo'"
          :menubar="false"
          :height="200"
        />
      </el-col>
    </el-row>
    <div class="save_btn">
      <el-button type="success" size="medium" round @click="saveQuestion">保存</el-button>
    </div>
  </el-card>
</template>

<script>
import TextSelect from '@/components/Form/TextSelect'
import ImageSelect from '@/components/Form/ImageSelect'
import AudioSelect from '@/components/Form/AudioSelect'
import FileViewer from '@/components/FileViewer'
import {questionLoad, questionSave} from '@/api/training/exam'

export default {
  name: 'QuestionEdit',
  components: {
    TextSelect,
    ImageSelect,
    AudioSelect,
    FileViewer
  },
  data() {
    return {
      questionInfo: {
        questionId: undefined,
        type: '1',
        optionType: '0',
        content: undefined,
        analysis: undefined,
        answer: undefined,
        difficulty: 1,
        score: 1,
        tagId: undefined,
        options: []
      },
      optionsAnswer: [],
      toolbar: 'bold italic underline strikethrough blockquote |forecolor backcolor |alignleft aligncenter alignright alignjustify |fillblank| undo redo',
      optionDialogVisible: false,
      current_option_type: '0',
      current_option_value: undefined,
      current_option_label: undefined,
      current_option_src: undefined
    }
  },
  methods: {
    init(questionId, tagId) {
      this.questionInfo = {
        questionId: undefined,
        type: '1',
        optionType: '0',
        content: undefined,
        analysis: undefined,
        answer: undefined,
        difficulty: 1,
        score: 1,
        tagId: undefined,
        options: []
      }
      this.changeType()

      this.$nextTick(() => {
        this.questionInfo.questionId = questionId || null
        this.loadForm(questionId, tagId)
      })
    },
    loadForm(questionId, tagId) {
      this.questionInfo.type = '0'
      questionLoad({id: questionId}).then(response => {
        this.questionInfo = this.$api.objectUpdate(this.questionInfo, response.param)
        if (!this.questionInfo.tagId) {
          this.questionInfo.tagId = tagId
        }
        if (this.questionInfo.type === '1') {
          this.optionsAnswer = this.questionInfo.answer?.split('{:}') ?? []
        }
      })
    },
    changeType() {
      this.questionInfo.options = []
      this.questionInfo.answer = undefined
      this.questionInfo.analysis = undefined
      this.optionsAnswer = []
    },
    combineAnswer(val) {
      this.questionInfo.answer = val
    },
    combineCheckboxAnswer(val) {
      this.questionInfo.answer = val?.join('{:}')??undefined
    },
    combineBlankAnswer() {
      let answer = []
      this.questionInfo.options.forEach(option => {
        answer.push(option.value)
      })
      this.questionInfo.answer = answer?.join('{:}')??undefined
    },
    addOption() {
      this.current_option_label = undefined
      this.current_option_value = undefined
      this.current_option_src = undefined
    },
    addOptionConfirm() {
      this.questionInfo.optionType = this.current_option_type
      if (this.current_option_value) {
        let that = this
        this.questionInfo.options.push({
          type: that.current_option_type,
          label: that.current_option_label,
          value: that.current_option_value,
          src: that.current_option_src
        })
      }
      this.closeOptionDialog()
    },
    closeOptionDialog() {
      if (this.current_option_src)
        this.$refs.file_viewer.clearFileList()

      this.current_option_label = undefined
      this.current_option_value = undefined
      this.current_option_src = undefined
      this.optionDialogVisible = false
    },
    clearOption() {
      this.$confirm('是否清空所有选项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        this.questionInfo.options = []
        this.current_option_label = undefined
        this.current_option_value = undefined
        this.current_option_src = undefined
      }).catch(e => {})
    },
    renderOption(render) {
      if (this.questionInfo.type === '3') {
        let index = render.indexOf('(____)')
        let num = 0
        while (index !== -1) {
          num++
          index = render.indexOf('(____)', index + 1)
        }

        if (num !== this.questionInfo.options.length) {
          this.questionInfo.options = []
          for (let i = 0; i < num; i++) {
            this.questionInfo.options.push({
              type: '0',
              label: undefined,
              value: ''
            })
          }
        }
      }
    },
    saveQuestion() {
      if (!this.questionInfo.content) {
        this.$modal.msgWarning('请填写试题题目')
        return
      }
      if (!this.questionInfo.answer) {
        this.$modal.msgWarning('请填写试题答案')
        return
      }

      questionSave(this.questionInfo).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.$emit('update')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.question-options-item {
  background: #e5e9f2;
}

.blank_option-item {
  display: block;
  margin-bottom: 5px;

  /deep/.underline {
    .el-input__inner {
      border-radius: 0px;
      border-top-width: 0px;
      border-left-width: 0px;
      border-right-width: 0px;
      border-bottom-width: 1px;
    }
  }
}

.save_btn {
  position: absolute;
  bottom: 50px;
  right: 30px;
  z-index: 10000;
}
</style>
